﻿using MediatR;
using PublicCommon;
using T_vehicle.Domain;
using T_vehicle.Infrastructure.Impl;
using T_vehicle.Infrastructure.Interfacec;
using T_vehicle.Read.API.Application.Command.AccidentCommand;

namespace T_vehicle.Read.API.Application.CommandHandlers.AccidentCommandHandlers
{
    public class GetAccidentCommandHandlers:IRequestHandler<GetAccidentCommand,PageResult<Accident>>
    {
        private readonly IAccidentRepository accidentRepository;

        public GetAccidentCommandHandlers(IAccidentRepository accidentRepository)
        {
            this.accidentRepository = accidentRepository;
        }

        public async Task<PageResult<Accident>> Handle(GetAccidentCommand request, CancellationToken cancellationToken)
        {
            var list = accidentRepository.GetAllAsync().Result.Where(x => x.IsDel == false).AsQueryable();
            if (!string.IsNullOrEmpty(request.LicenNumber))
            {
                list = list.Where(x => x.LicenNumber.Contains(request.LicenNumber));
            }
            if (!string.IsNullOrEmpty(request.AccidentTitle))
            {
                list = list.Where(x => x.AccidentTitle.Contains(request.AccidentTitle));
            }
            if (!string.IsNullOrEmpty(Convert.ToString(request.IncidentDate)))
            {
                list = list.Where(x => Convert.ToString(x.IncidentDate) == Convert.ToString(request.IncidentDate));
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            var res = list.Skip(request.pageIndex - 1 * request.pageSize).Take(request.pageSize).ToList();
            return  new PageResult<Accident>
            {
                TotalCount = totalCount,
                PageCount = pageCount,
                List = res
            };

        }
    }
}
